from fastapi import APIRouter, HTTPException, status, Depends
from pydantic import BaseModel
from database import get_db

router = APIRouter(
    prefix="/auth",
    tags=["auth"],
)


class CustomerLogin(BaseModel):
    customerName: str
    password: str


@router.post("/login", status_code=status.HTTP_200_OK)
async def login(customer: CustomerLogin, conn=Depends(get_db)):
    try:
        user_record = None
        cursor = conn.cursor(dictionary=True)
        query = "SELECT customerID, customerName, PID, telephone, address FROM customerInfo WHERE customerName = %s AND pass = %s"
        cursor.execute(query, (customer.customerName, customer.password))
        user_record = cursor.fetchone()
        if user_record:
            return {"message": "Login successful", "customer": user_record}
        else:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Incorrect customer name or password",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    finally:
        cursor.close()
